//
//  HBHotCoinChartLineView.m
//
//  Created by tianlong on 2024/12/3.
//

#import "HBHotCoinChartLineView.h"
#import "HBHotCoinChartUtils.h"
#import "UIView+Extension.h"
#import "UIFont+helper.h"
#import "UIColor+helper.h"

@interface HBHotCoinChartLineView ()

/// 保存绘制折线图的点的集合
@property (nonatomic, strong) NSArray *points;

@end

@implementation HBHotCoinChartLineView

- (instancetype)initWithChartModel:(HBHotCointChartModel *)chartModel {
    self = [super initWithChartModel:chartModel];
    if (self) {
        // 添加点击手势识别器
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
        [self addGestureRecognizer:tapGesture];
    }
    return self;
}

- (void)drawRect:(CGRect)rect {
    
    // 找Y轴的最大值
    NSNumber *maxYValue = @(0);
    for (HBHotCointChartItemModel *item in self.chartModel.pointList) {
        maxYValue = @(MAX(maxYValue.floatValue, item.originalValue.floatValue));
    }
    NSLog(@"找到了最大值==%@",maxYValue.stringValue);
    
    NSMutableArray *arrM = [NSMutableArray array];
    for (NSInteger i = 0; i < self.chartModel.pointList.count; i++) {
        HBHotCointChartItemModel *item = self.chartModel.pointList[i];
        NSMutableDictionary *pointsDictM = [NSMutableDictionary dictionary];
        CGFloat yScale = rect.size.height / maxYValue.doubleValue;
        CGFloat x = i * (rect.size.width / (self.chartModel.pointList.count - 1));
        CGFloat y = rect.size.height - item.originalValue.floatValue * yScale;
        
        [pointsDictM setValue:@(x) forKey:@"x"];
        [pointsDictM setValue:@(y) forKey:@"y"];
        [pointsDictM setValue: ^{
            if (self.clickedPoint) {
                self.clickedPoint(CGPointMake(x, y), item);
            }
        } forKey:@"tapAction"];
        [arrM addObject:pointsDictM];
    }
    self.points = [NSArray arrayWithArray:arrM];
    
    // 画折线,lineColor=baseColorMajorTheme100
    [HBHotCoinChartUtils drawLineChartInView:self dataPoints:self.points lineColor:UIColor.blueColor lineWidth:1.5];
}

// 点击手势处理方法
- (void)handleTap:(UITapGestureRecognizer *)gesture {
    CGPoint tapLocation = [gesture locationInView:self];
    if (!CGRectContainsPoint(self.bounds, tapLocation)) {
        NSLog(@"触摸的点不在范围内");
    }
    NSMutableArray *arrX = [NSMutableArray array];
    CGFloat min = [self.points.firstObject[@"x"] floatValue];
    for (NSDictionary *pointDict in self.points) {
        CGFloat pointX = [pointDict[@"x"] floatValue];
        min = MIN(min, tapLocation.x);
        [arrX addObject:@(pointX)];
    }
    [arrX addObject:@(tapLocation.x)];
    NSArray *sortArr = [arrX sortedArrayUsingComparator:^NSComparisonResult(NSNumber *num1, NSNumber *num2) {
        return [num1 compare:num2];
    }];
    
    NSInteger midIdx = [sortArr indexOfObject:@(tapLocation.x)];
    NSNumber *idxLeftNum = nil;
    if (midIdx - 1 < sortArr.count) {
        idxLeftNum = sortArr[midIdx - 1];
    }
    
    NSNumber *idxRightNum = nil;
    if (midIdx + 1 < sortArr.count) {
        idxRightNum = sortArr[midIdx + 1];
    }
    
    if (idxLeftNum && idxRightNum) {
        NSNumber *choose = idxLeftNum;// 默认离左侧更近
        if (fabs(tapLocation.x - idxLeftNum.floatValue) > fabs(tapLocation.x - idxRightNum.floatValue)) {
            // idxRight 更近
            choose = idxRightNum;
        }
        for (NSDictionary *pointDict in self.points) {
            CGFloat pointX = [pointDict[@"x"] floatValue];
            if (choose.floatValue == pointX) {
                void (^tapAction)(void) = pointDict[@"tapAction"];
                if (tapAction) {
                    tapAction();
                }
                break;
            }
        }
    }
}

- (NSArray *)points {
    if (!_points) {
        _points = [NSArray array];
    }
    return _points;
}

@end


@implementation HBHotCoinChartPopupView

- (instancetype)init {
    self = [super init];
    if (self) {
        UIView *backgroundView = [[UIView alloc] init];
        backgroundView.backgroundColor = UIColor.whiteColor;// kColorCommunityCardBackground
        backgroundView.alpha = 0.8;
        [self addSubview:backgroundView];
        self.backgroundView = backgroundView;
        
        self.layer.borderWidth = 1;
        self.layer.borderColor = UIColor.redColor.CGColor;
    }
    return self;
}

- (void)setItemModel:(HBHotCointChartItemModel *)itemModel {
    _itemModel = itemModel;
    
    if (!self.titleLabel) {
        UILabel *titleLabel = [[UILabel alloc] init];
        titleLabel.font = [UIFont font_RobotoRegularWithSize:11];
        titleLabel.textColor = UIColor.blackColor;// baseColorThreeLevelText
        [self addSubview:titleLabel];
        self.titleLabel = titleLabel;
    }
    self.titleLabel.text = itemModel.popupDate;
    [self.titleLabel sizeToFit];
    
    if (!self.subTitleLabel) {
        UILabel *subTitleLabel = [[UILabel alloc] init];
        subTitleLabel.font = [UIFont font_RobotoRegularWithSize:11];
        subTitleLabel.textColor = UIColor.blackColor;// kColorPrimaryText
        [self addSubview:subTitleLabel];
        self.subTitleLabel = subTitleLabel;
    }
    self.subTitleLabel.text = itemModel.popupContent;
    [self.subTitleLabel sizeToFit];
    
    CGFloat padding = 8;
    CGFloat maxW = MAX(self.subTitleLabel.width, self.titleLabel.width);
    self.titleLabel.frame = CGRectMake(padding, padding, self.titleLabel.width, self.titleLabel.height);
    self.subTitleLabel.frame = CGRectMake(padding, 6 + self.titleLabel.height, self.subTitleLabel.width, self.subTitleLabel.height);
    self.size = CGSizeMake(maxW + padding * 2, CGRectGetMaxY(self.subTitleLabel.frame) + padding);
    
    self.backgroundView.frame = self.bounds;
}

@end
